package com.vq3.digitalizationsoftwareintegrates.Utils.PermissionControl;


import com.vq3.digitalizationsoftwareintegrates.Entity.Info.ResultInfo;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.Impl.PackagedDataImpl;
import com.vq3.digitalizationsoftwareintegrates.Utils.PackagedDataUtil.PackagedData;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**登录验证码
 * */
@Component
public class VerifyCodeFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String defaultFilterProcessUrl = "/login";
        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            // 验证码验证
            String requestCaptcha = request.getParameter("check");
            String genCaptcha = (String) request.getSession().getAttribute("CODE");
            ResultInfo resultInfo = new ResultInfo();
            PackagedData packagedData = new PackagedDataImpl();
            if (StringUtils.isEmpty(requestCaptcha)){
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("验证码不能为空！");
                packagedData.writeValue(resultInfo,response);
            }else {
                if (null == genCaptcha){
                    resultInfo.setFlag(false);
                    resultInfo.setErrorMsg("验证码错误！");
                    packagedData.writeValue(resultInfo, response);
                }else if (!genCaptcha.equalsIgnoreCase(requestCaptcha)) {
                    resultInfo.setFlag(false);
                    resultInfo.setErrorMsg("验证码错误！");
                    packagedData.writeValue(resultInfo, response);
                }else {
                    chain.doFilter(request, response);
                }
            }
        }else {
            chain.doFilter(request, response);
        }

    }

}

